package com.tongcao.cn.service.impl;

import com.alibaba.common.convert.Convert;
import com.tongcao.cn.service.ISmsService;
import com.tongcao.cn.thread.ThreadPoolManager;
import lombok.extern.log4j.Log4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @Author:tongcao
 * @Date:2019/1/4 14:27
 * Description:
 */
@Component
@Log4j
public class SmsService implements ISmsService {

    private ThreadPoolManager manager = ThreadPoolManager.INSTANCE;

    private static final String DEF_CHATSET = "UTF-8";
    private static final int DEF_CONN_TIMEOUT = 30000;
    private static final int DEF_READ_TIMEOUT = 30000;
    public static final String ERROR_CODE = "error_code";
    public static final String REASON = "reason";
    public static final String RESULT = "result";

    private static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

    @Value("${send.url}")
    private String url;

    @Value("${send.templateId}")
    private String defaultTemplateId;

    @Value("${send.appKey}")
    private String appKey;

    /**
     * @param params
     * @param method GET or POST
     * @return
     */
    @Override
    public String sendSms(Map<String, Object> params, String method, String templateId) {
        String result = null;
        try {
            if (MapUtils.isNotEmpty(params)) {
                params.put("tpl_id", StringUtils.isEmpty(templateId) ? Convert.asInt(defaultTemplateId) : templateId);
                params.put("key", appKey);
                params.put("dtype", "json");
            }
            result = net(url, params, method);
            JSONObject object = JSONObject.fromObject(result);
            if (object.getInt(ERROR_CODE) == 0) {
                return Convert.asString(object.get(RESULT));
            } else {
                return Convert.asString(object.get(ERROR_CODE) + ":" + object.get(REASON));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送标准短息你模板
     *
     * @param params
     * @param method
     * @return
     */
    @Override
    public String sendSms(Map<String, Object> params, String method) {
        return sendSms(params, method, defaultTemplateId);
    }

    /**
     * 异步发送短信
     *
     * @param params
     * @param method
     * @return
     */
    @Override
    public void asyncSendSms(Map<String, Object> params, String method) {
        CompletableFuture.runAsync(() -> {
            String result = sendSms(params, method, defaultTemplateId);
            log.info(result);
        }, manager.getBizPoolService());
    }

    /**
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return 网络请求字符串
     * @throws Exception
     */
    private static String net(String strUrl, Map params, String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

    /**
     * 将map型转为请求参数型
     *
     * @param data
     * @return
     */
    public static String urlencode(Map<String, String> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
